package org.kuaishou;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.Session;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.kuaishou.httputil.HttpClientUtil;
import org.kuaishou.httputil.IHttpRequest;
import org.kuaishou.httputil.RequestArgs;
import org.kuaishou.httputil.ResponseResult;

import java.net.URL;
import java.util.*;

public class LoadVIdeoList {
    public static final SnowflakeGenerator SNOWFLAKE_GENERATOR = new SnowflakeGenerator();
    public static final String USER_DIR = System.getProperty("user.dir");

    public List<String> loadList(String url, String tableName, String userId) throws Exception {
        List<String> list = Db.use().query(String.format("SELECT VIDEO_ID FROM %s", tableName), String.class);
        HashSet<String> listSet = new HashSet<>(list);
        System.out.println(list.size());

        String cookieStr = FileUtils.readFileToString(FileUtils.getFile(USER_DIR, "config", "request_cookie.txt"), "UTF-8");
        cookieStr = StringUtils.defaultString(cookieStr).trim();
        if (cookieStr.isEmpty()) throw new Exception("Cookie 内容为空");

        LinkedHashMap<String, String> headerMap = new LinkedHashMap<>();
        headerMap.put("Cookie", cookieStr);
        headerMap.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");
        final String requestStr;

        boolean isLikeTable = Run.TABLE_NAME.equalsIgnoreCase(tableName);

        if (isLikeTable) {
            requestStr = FileUtils.readFileToString(FileUtils.getFile(USER_DIR, "config", "request.txt"), "UTF-8");
        } else {
            requestStr = FileUtils.readFileToString(FileUtils.getFile(USER_DIR, "config", "request_user.txt"), "UTF-8");
        }

        IHttpRequest httpRequest = new HttpClientUtil();
        RequestArgs args = new RequestArgs();
        args.setUrl(url);
        args.setHeaderMap(headerMap);

        //String format = String.format(requestStr, "");
        String format = requestBodyFormat(requestStr, "", userId);

        List<JSONObject> feedList = new ArrayList<>();

        while (true) {
            args.setJsonBody(format);
            ResponseResult result = httpRequest.sendPost(args);

            String status = result.getStatus();
            System.out.println(status);

            String body = result.getBody();
            //System.out.println(body);
            JSONObject jsonObject = JSONObject.parseObject(body);
            JSONObject dataObject = jsonObject.getJSONObject("data");
            if (dataObject == null) throw new Exception("data 为空");
            JSONObject visionProfileLikePhotoList;
            if (isLikeTable) {
                visionProfileLikePhotoList = dataObject.getJSONObject("visionProfileLikePhotoList");
            } else {
                visionProfileLikePhotoList = dataObject.getJSONObject("visionProfilePhotoList");
            }
            if (visionProfileLikePhotoList == null) throw new Exception("PhotoList 为空");
            JSONArray feedsArray = visionProfileLikePhotoList.getJSONArray("feeds");
            //
            for (int i = 0; i < feedsArray.size(); i++) {
                JSONObject feed = feedsArray.getJSONObject(i);
                JSONObject photo = feed.getJSONObject("photo");
                String id = photo.getString("id");
                if (listSet.contains(id)) {
                    System.out.println("已经读取到最新数据，加载了" + feedList.size() + " 条数据");
                    continue;
                }
                feedList.add(feed);
            }
            //
            String pcursor = visionProfileLikePhotoList.getString("pcursor");
            if ("no_more".equals(pcursor)) break;
            //format = String.format(requestStr, pcursor);
            format = requestBodyFormat(requestStr, pcursor, userId);
        }


        Collections.reverse(feedList); // 倒序排列

        Number number = Db.use().queryNumber(String.format("SELECT COUNT(*) FROM %s", tableName));
        long maxSort = number.longValue();

        //默认数据源
        Session session = Session.create();
        List<String> idList = new LinkedList<String>();
        for (int i = 0; i < feedList.size(); i++) {
            JSONObject feed = feedList.get(i);
            JSONObject author = feed.getJSONObject("author");
            JSONObject photo = feed.getJSONObject("photo");
            String videoId = photo.getString("id");

            String id = SNOWFLAKE_GENERATOR.next().toString();
            String nickname = author.getString("name");
            String headerUrl = author.getString("headerUrl");
            String uid = author.getString("id");
            String caption = photo.getString("caption");
            String likeCount = photo.getString("likeCount");
            String coverUrl = photo.getString("coverUrl");
            String videoUrl = photo.getString("photoH265Url");
            String animatedCoverUrl = photo.getString("animatedCoverUrl");
            String timestamp = photo.getString("timestamp");
            String timestampLable = DateFormatUtils.format(new Date(Long.valueOf(timestamp)), "yyyy-MM-dd HH:mm");
            //
            String headerName = "header_" + id + ".jpg";
            String videoName = id + ".mp4";
            String coverName = "cover_" + id + ".jpg";
            String animatedCover = "animatedCove_" + id + ".webp";
            //

            //
            Entity entity = Entity.create(tableName);

            entity.put("HEADER_URL", headerUrl);
            entity.put("COVER_URL", coverUrl);
            entity.put("VIDEO_URL", videoUrl);
            entity.put("ANIMATED_COVER_URL", animatedCoverUrl);
            entity.put("ID", id);
            entity.put("NICKNAME", nickname);
            entity.put("UID", uid);
            entity.put("VIDEO_CONTENT", feed.toString());

            entity.put("VIDEO_NAME", videoName);
            entity.put("HEADER_NAME", headerName);
            entity.put("COVER_NAME", coverName);
            entity.put("ANIMATED_COVER", animatedCover);

            entity.put("VIDEO_ID", videoId);
            entity.put("LIKE_COUNT", likeCount);
            entity.put("CREATE_TIME", timestamp);
            entity.put("CREATE_TIME_LABLE", timestampLable);
            entity.put("SORT", ++maxSort);
            entity.put("CAPTION", caption);
            entity.put("GET_TIME", new Date());

            int c = session.insert(entity);
            idList.add(id);
        }
        session.close();//关闭会话

        return idList;
    }


    public void loadVodeo(String tableName, String pyVideoRoot) throws Exception {

        String PY_VIDEO = "/video";
        String PY_VIDEO_IMG = "/cover";
        String USER_IMG = "/header";
        String PY_IMAGES = "/images";
        String ANIMATED_COVE = "/animated_cover";

        PY_VIDEO = pyVideoRoot + PY_VIDEO;
        PY_VIDEO_IMG = pyVideoRoot + PY_VIDEO_IMG;
        USER_IMG = pyVideoRoot + USER_IMG;
        PY_IMAGES = pyVideoRoot + PY_IMAGES;
        ANIMATED_COVE = pyVideoRoot + ANIMATED_COVE;

        String sqlList = String.format("SELECT * FROM %s WHERE `LOAD_TIME` IS NULL ORDER BY SORT", tableName);
        System.out.println(sqlList);
        List<Entity> query = Db.use().query(sqlList);//需要下载的视频集合


        //默认数据源
        Session session = Session.create();
        for (Entity map : query) {
            String id = map.getStr("ID");
            String headerUrl = map.getStr("HEADER_URL");
            String coverUrl = map.getStr("COVER_URL");
            String animatedCoverUrl = map.getStr("ANIMATED_COVER_URL");
            String videoUrl = map.getStr("VIDEO_URL");
            String caption = map.getStr("CAPTION");

            String videoName = map.getStr("VIDEO_NAME");
            String coverName = map.getStr("COVER_NAME");
            String headerName = map.getStr("HEADER_NAME");
            String animatedCover = map.getStr("ANIMATED_COVER");
            try {
                if (StringUtils.isNotBlank(headerUrl)) FileUtils.copyURLToFile(new URL(headerUrl), FileUtils.getFile(USER_IMG, headerName));
                if (StringUtils.isNotBlank(coverUrl)) FileUtils.copyURLToFile(new URL(coverUrl), FileUtils.getFile(PY_VIDEO_IMG, coverName));
                if (StringUtils.isNotBlank(animatedCoverUrl)) FileUtils.copyURLToFile(new URL(animatedCoverUrl), FileUtils.getFile(ANIMATED_COVE, animatedCover));
                if (StringUtils.isNotBlank(videoUrl)) FileUtils.copyURLToFile(new URL(videoUrl), FileUtils.getFile(PY_VIDEO, videoName));
                //
                Entity entity = Entity.create();//修改的数据
                entity.put("TYPE", "1");//类型：1视频，2图文
                entity.put("LOAD_TIME", new Date());

                Entity where = Entity.create(tableName).set("ID", id);//where条件
                session.update(entity, where);
                System.out.println("下载完成->" + caption);
            } catch (Exception ex) {
                System.err.println("下载异常->" + caption);
                ex.printStackTrace();
            }
        }
        session.close();
    }


    public void updateTable(String tableName) throws Exception {
        String sqlList = String.format("SELECT * FROM %s ", tableName);
        System.out.println(sqlList);
        List<Entity> query = Db.use().query(sqlList);//需要下载的视频集合

        //默认数据源
        Session session = Session.create();
        for (Entity map : query) {
            String id = map.getStr("ID");
            String caption = map.getStr("CAPTION");
            String videoContent = map.getStr("VIDEO_CONTENT");

            JSONObject feed = JSONObject.parseObject(videoContent);
            JSONObject photo = feed.getJSONObject("photo");
            JSONObject author = feed.getJSONObject("author");
            String uid = author.getString("id");
            String videoId = photo.getString("id");
            try {
                //
                Entity entity = Entity.create();//修改的数据
                entity.put("UID", uid);

                Entity where = Entity.create(tableName).set("ID", id);//where条件
                session.update(entity, where);
                System.out.println("下载完成->" + caption);
            } catch (Exception ex) {
                System.out.println("下载异常->" + caption);
                ex.printStackTrace();
            }
        }
        session.close();
    }

    public static String requestBodyFormat(String requestStr, String pcursor, String userId) {
        String format;
        if (StringUtils.isBlank(userId)) {
            format = String.format(requestStr, pcursor);
        } else {
            format = String.format(requestStr, pcursor, userId);
        }
        return format;
    }
}
